package com.fadis.cmd;

import com.fadis.data.FBloomFilter;
import com.fadis.FadisException;
import com.fadis.data.bloomfilter.BloomFilter;
import com.fadis.db.FadisDB;
import com.fadis.protocol.LongNumber;
import com.fadis.protocol.RespArray;
import com.fadis.watch.FadisWatcher;

import java.util.ArrayList;
import java.util.List;

public class CmdBloomFilter {

    public static final class bfadd implements CmdHandler {
        @Override
        public String run(FadisActionFrame frame) throws FadisException {
            String key = frame.getArg(1);
            String value = frame.getArg(2);

            BloomFilter bf = FadisDB.tryToGetOrCreateBloomFilter(key, true);
            boolean r = FBloomFilter.add(bf, value);
            if(r) FadisWatcher.onKeyUpdated(key);
            return LongNumber.encodeInt(r ? 0 : 1);
        }
    }


    public static final class bfmadd implements CmdHandler {
        @Override
        public String run(FadisActionFrame frame) throws FadisException {
            String key = frame.getArg(1);
            String[] values = new String[frame.getArgsCount() - 1];
            for (int i = 1; i < frame.getArgsCount(); i++) {
                values[i-1] = frame.getArg(i);
            }

           

            BloomFilter bf = FadisDB.tryToGetOrCreateBloomFilter(key, true);
            boolean[] r = FBloomFilter.madd(bf, values);

            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < r.length; i++) {
                list.add(r[i] ? 1 : 0);
            }
            return RespArray.encodeCommon(list);
        }
    }

    public static final class bfexists implements CmdHandler {
        @Override
        public String run(FadisActionFrame frame) throws FadisException {
            String key = frame.getArg(1);
            String value = frame.getArg(2);

           

            BloomFilter bf = FadisDB.tryToGetOrCreateBloomFilter(key, false);
            boolean r = FBloomFilter.exists(bf, value);
            return LongNumber.encodeInt(r ? 1 : 0);
        }
    }


    public static final class bfmexists implements CmdHandler {
        @Override
        public String run(FadisActionFrame frame) throws FadisException {
            String key = frame.getArg(1);
            String value = frame.getArg(2);

            BloomFilter bf = FadisDB.tryToGetOrCreateBloomFilter(key, false);
            boolean[] r = FBloomFilter.mexists(bf, value);

            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < r.length; i++) {
                list.add(r[i] ? 1 : 0);
            }
            return RespArray.encodeCommon(list);
        }
    }
}
